<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------

// 应用公共文件

/**
 * ajax请求json序列化数据
* @param string $status
* @param array $data  数组,当为字符串时会把此值赋值给error
*/
function ajaxResponse($status, $data) {
	if (is_array($data) && count($data)){
		$re = [
				'status'  => $status,
				'message' => '',
				'count'   => count($data),
				'data'    => $data,
		];
	} else {
		$re = [
				'status'  => $status,
				'message' => $data,
				'count'   => 0,
				'data'    => (object)[],
		];
	}
	echo json_encode($re, JSON_UNESCAPED_UNICODE);
	die();
}
/**
 * 引用discuz的authcode方法，并进行了改进，
 * 原版的函数代码可能会生成+、/、&这样的字符，导致通过URL传值取回时被转义，导致无法解密。
 * 把这几个字符替换成其它字符，解密时再替换回去
 * @param string $string    字符串
 * @param string $operation 加解密操作(加密ENCODE、解密DECODE)
 * @param string $key   密钥
 * @param int $expiry    有效时间(秒)
 * @return string|mixed
 */
function authcode($string, $operation = 'DECODE', $key = '', $expiry = 0){

	if($operation == 'DECODE') {
		$string = str_replace('[a]','+',$string);
		$string = str_replace('[b]','&',$string);
		$string = str_replace('[c]','/',$string);
	}
	$ckey_length = 4;
	$key = md5($key ? $key : 'jbk3311');
	$keya = md5(substr($key, 0, 16));
	$keyb = md5(substr($key, 16, 16));
	$keyc = $ckey_length ? ($operation == 'DECODE' ? substr($string, 0, $ckey_length): substr(md5(microtime()), -$ckey_length)) : '';
	$cryptkey = $keya.md5($keya.$keyc);
	$key_length = strlen($cryptkey);
	$string = $operation == 'DECODE' ? base64_decode(substr($string, $ckey_length)) : sprintf('%010d', $expiry ? $expiry + time() : 0).substr(md5($string.$keyb), 0, 16).$string;
	$string_length = strlen($string);
	$result = '';
	$box = range(0, 255);
	$rndkey = array();
	for($i = 0; $i <= 255; $i++) {
		$rndkey[$i] = ord($cryptkey[$i % $key_length]);
	}
	for($j = $i = 0; $i < 256; $i++) {
		$j = ($j + $box[$i] + $rndkey[$i]) % 256;
		$tmp = $box[$i];
		$box[$i] = $box[$j];
		$box[$j] = $tmp;
	}
	for($a = $j = $i = 0; $i < $string_length; $i++) {
		$a = ($a + 1) % 256;
		$j = ($j + $box[$a]) % 256;
		$tmp = $box[$a];
		$box[$a] = $box[$j];
		$box[$j] = $tmp;
		$result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));
	}
	if($operation == 'DECODE') {
		if((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26).$keyb), 0, 16)) {

			return substr($result, 26);
		} else {
			return '';
		}
	} else {
		$ustr = $keyc.str_replace('=', '', base64_encode($result));
		$ustr = str_replace('+','[a]',$ustr);
		$ustr = str_replace('&','[b]',$ustr);
		$ustr = str_replace('/','[c]',$ustr);
		return $ustr;
	}
}

/**
 * 检测post数据参数是否存在或者为空,不存在或者为空返回参数名，否则返回false
 * @param array $chk_params 参数数组或者以角号','隔开的字符串
 * @return string | boolean 返回
 */
function chkEmptyPostParams($chk_params = array())
{
	$empty_param = false;
	//字符串转换数组
	if (is_string($chk_params))$chk_params = explode(',', $chk_params);
	foreach ((array)$chk_params as $value){
		if ( isset($_POST[$value]) && !($_POST[$value] == '') ) continue;
		else {
			$empty_param = $value;
			break;
		}
	}
	return $empty_param;
}
/**
 * 发送curl请求
 * @param  string $url    请求地址
 * @param  array  $params 请求参数
 * @param  string $method 请求类型GET/POST
 * @param  array  $header 头部信息array('Content-type: text/plain', 'Content-length: 100') 
 * @param  number $timeout请求超时设置
 * @return array  $data   返回请求结果
 */
function curl_http($url, $params = [], $method = 'GET', $header = [], $timeout = 30, $multi = false) {
	$opts = array (
			CURLOPT_TIMEOUT => $timeout,
			CURLOPT_RETURNTRANSFER => 1,
			CURLOPT_SSL_VERIFYPEER => false,
			CURLOPT_SSL_VERIFYHOST => false,
			CURLOPT_HTTPHEADER => $header
	);
	switch (strtoupper ( $method )) {
		case 'GET' :
			$opts [CURLOPT_URL] = $url . (strpos ( $url, '?' ) ? '&' : '?') . http_build_query ( $params );
			break;
		case 'POST' :
			$params = $multi ? $params : http_build_query ( $params );
			$opts [CURLOPT_URL] = $url;
			$opts [CURLOPT_POST] = 1;
			$opts [CURLOPT_POSTFIELDS] = $params;
			break;
		default :
			throw new Exception ('不支持该请求方式');
	}
	$ch = curl_init ();
	curl_setopt_array ( $ch, $opts );
	$data = curl_exec ( $ch );
	$error = curl_error ( $ch );
	curl_close ( $ch );

	return $data;
}
/**
 * gbk编码转换至utf-8
 * gbk编码中文json_encode 出现null 的解决方法
 * @param $data
 */
function gbk_utf8($data){
	if(is_array($data)){
		return array_map('gbk_utf8', $data);
	}
	return iconv('gbk','utf-8',$data);
}
/**
 * 获取客户端ip
 * @return 空 ||IP
 */
function getClientIp(){
	if (isset($_SERVER["HTTP_CLIENT_IP"])){
		$ip = $_SERVER["HTTP_CLIENT_IP"];
	}elseif (isset($_SERVER["REMOTE_ADDR"])){
		$ip = $_SERVER["REMOTE_ADDR"];
	}elseif (getenv("HTTP_X_FORWARDED_FOR")){
		$ip = getenv("HTTP_X_FORWARDED_FOR");
	}elseif (getenv("HTTP_CLIENT_IP")){
		$ip = getenv("HTTP_CLIENT_IP");
	}elseif (getenv("REMOTE_ADDR")){
		$ip = getenv("REMOTE_ADDR");
	}else{
		$ip = "";
	}
	return $ip;
}
/**
 * 根据百度接口，获取客户端经纬度
 * @return false || $res['lat'=>xxx,'lng'=>xxx,'content'=>...]
 */
function getClientLatLng() {
	$ip = getClientIp();
	if (!$ip) return false;
	//根据百度接口获取ip位置
	$bdUrl 	 = 'http://api.map.baidu.com/location/ip?ak=%s&ip=%s&coor=bd09ll';
	$content = file_get_contents(sprintf($bdUrl, config('bdAk'), $ip));
	$arr 	 = json_decode($content, true);
	if(!$arr || $arr['status'] != 0) return false;
	 return [
			'lat' 		=> $arr['content']['point']['y'],
			'lng' 		=> $arr['content']['point']['x'],
			'detail' 	=> $arr['content']['address_detail']
	];
}
/**
 * 是否手机访问
 * @return boolean|string
 */
function isMobile() {
	if(isset($_GET['mobile']) && $_GET['mobile'] == 'pc') {
		return false;
	}
	function dstrpos($string, $arr, $returnvalue = false) {
		if(empty($string)) return false;
		foreach((array)$arr as $v) {
			if(strpos($string, $v) !== false) {
				$return = $returnvalue ? $v : true;
				return $return;
			}
		}
		return false;
	}
	static $touchbrowser_list =array('iphone', 'android', 'phone', 'mobile', 'wap', 'netfront', 'java', 'opera mobi', 'opera mini',
			'ucweb', 'windows ce', 'symbian', 'series', 'webos', 'sony', 'blackberry', 'dopod', 'nokia', 'samsung',
			'palmsource', 'xda', 'pieplus', 'meizu', 'midp', 'cldc', 'motorola', 'foma', 'docomo', 'up.browser',
			'up.link', 'blazer', 'helio', 'hosin', 'huawei', 'novarra', 'coolpad', 'webos', 'techfaith', 'palmsource',
			'alcatel', 'amoi', 'ktouch', 'nexian', 'ericsson', 'philips', 'sagem', 'wellcom', 'bunjalloo', 'maui', 'smartphone',
			'iemobile', 'spice', 'bird', 'zte-', 'longcos', 'pantech', 'gionee', 'portalmmm', 'jig browser', 'hiptop',
			'benq', 'haier', '^lct', '320x320', '240x320', '176x220', 'windows phone');
	static $wmlbrowser_list = array('cect', 'compal', 'ctl', 'lg', 'nec', 'tcl', 'alcatel', 'ericsson', 'bird', 'daxian', 'dbtel', 'eastcom',
			'pantech', 'dopod', 'philips', 'haier', 'konka', 'kejian', 'lenovo', 'benq', 'mot', 'soutec', 'nokia', 'sagem', 'sgh',
			'sed', 'capitel', 'panasonic', 'sonyericsson', 'sharp', 'amoi', 'panda', 'zte');
	static $pad_list = array('ipad');
	$useragent = strtolower($_SERVER['HTTP_USER_AGENT']);
	if(dstrpos($useragent, $pad_list, true)) {
		return false;
	}
	if((dstrpos($useragent, $touchbrowser_list, true))){
		return '2';
	}
	if((dstrpos($useragent, $wmlbrowser_list))) {
		return '3'; //wml版
	}
	$brower = array('mozilla', 'chrome', 'safari', 'opera', 'm3gate', 'winwap', 'openwave', 'myop');
	if(dstrpos($useragent, $brower)) return false;

	return false;
}
/**
 * 是否微信客户端
 * @return boolean|string
 */
function isWeixin(){
	if ( strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false ) {
		return true;
	}
	return false;
}
/**
 * 缓存管理(自定义修正版)
 * @param mixed     $name 缓存名称，如果为数组表示进行缓存设置
 * @param mixed     $value 缓存值
 * @param mixed     $options 缓存参数
 * @param string    $tag 缓存标签
 * @return mixed
 */
function safeCache($name, $value = '', $options = null, $tag = null){
	if (is_null($options)){
		$options = config('cache');	//引入配置参数（修正由于框架里面没有对有效时间设置）
	}
	return cache($name, $value, $options, $tag);
}
/**
 * 发送邮件
 * @param string $to		收件邮箱
 * @param string $subject	标题
 * @param string $body		内容
 * @param string $fromName  发送人名称
 */
function sendMail($to, $subject, $body, $fromName = '地图蛙')
{
	\think\Loader::import('PHPMailer.PHPMailerAutoload');
	$mail = new PHPMailer;
	$mail->Charset='UTF-8';
	//$mail->SMTPDebug = 3;                               // Enable verbose debug output
	$mail->isSMTP();                                      // Set mailer to use SMTP
	$mail->Host = 'smtp.exmail.qq.com';  // Specify main and backup SMTP servers
	$mail->SMTPAuth = true;                               // Enable SMTP authentication
	$mail->Username = 'hi@dituwa.com';                 // SMTP username
	$mail->Password = 't5e3QQ11';                           // SMTP password
	$mail->SMTPSecure = 'ssl';//'tls';                            // Enable TLS encryption, `ssl` also accepted
	$mail->Port = 465;                                    // TCP port to connect to
	$mail->setFrom('hi@dituwa.com', $fromName);
	$mail->addAddress($to);     // Add a recipient
	//$mail->addAddress('ellen@example.com');               // Name is optional
	$mail->addReplyTo('hi@dituwa.com', '回复信息');
	//$mail->addCC('cc@example.com');
	//$mail->addBCC('bcc@example.com');
	//$mail->addAttachment('/var/tmp/file.tar.gz');         // Add attachments
	//$mail->addAttachment('/tmp/image.jpg', 'new.jpg');    // Optional name
	$mail->isHTML(true);                                  // Set email format to HTML
	$mail->Subject = $subject;
	$mail->Body    = $body;
	$mail->AltBody = $body;
	//发送
	if(!$mail->send()) {
		return false;
	} else {
		return true;
	}
}

/************* 用户登录相关 *****************/
/**
 * 设置用户登录状态
 * @param int $uid          用户uid
 * @param string $username  用户名
 * @param string $expire    有效时间
 * @param array  $extend    扩展选项
 * @return $encrypt
 */
function setLoginInfo($uid, $username, $expire = 86400, $extend=[])
{
	$uid = 'uid\t'.$uid;
	$username = 'username\t'.$username;
	//扩展选项序列化
	$extend_tmp = [];
	foreach ($extend as $key => $value){
		$extend_tmp[] = $key.'\t'.$value;
	}
	$tmpStr = $uid.'\n'.$username.'\n'.'\n'.implode('\n', $extend_tmp);  //拼接字符串
	$encrypt = authcode($tmpStr, 'ENCODE', '', $expire);   //加密用户信息
	cookie(config('cookie_auth'), $encrypt, ['expire' => $expire]);
	cookie('islogin', 1, ['prefix'=>'', 'expire'=>$expire]);
	return $encrypt;
}
/**
 * 退出登录
 */
function setLoginOut()
{
	cookie(config('cookie_auth'), NULL);
	cache('loginUserInfo', null);
	cookie('islogin', 0, ['prefix'=>'']);
}
/**
 * 获取用户登录信息
 * @return $user[]
 */
function getLoginInfo()
{
	//读取cookie值
	$cookieAuth = cookie(config('cookie_auth'));
	$user = []; //用户信息
	if ($cookieAuth){
		//是否存在缓存
		$cache = md5($cookieAuth);
		if (cache($cache)) return cache($cache);
		$userStr = authcode($cookieAuth);
		if ($userStr){
			//解析字符串
			$strInfo = explode('\n', $userStr);
			foreach ($strInfo as $value){
				$userTmp = explode('\t', $value);
				if(!empty($userTmp[0]) && !empty($userTmp[1])) $user[$userTmp[0]] = $userTmp[1];
			}
			cache($cache, $user, ['expire'=> 60]);
		}else{
			$user = null;
		}
	} else {
		$user = null;
	}
	return $user;
}
